import {Directive, HostListener, Input} from '@angular/core';
import {ErrorService} from '../api/ErrorService';
import {HttpClient} from '@angular/common/http';

@Directive({
  selector: '[gnFileDownload]'
})
export class FileDownloadDirective {

  @Input() url: string;
  @Input() fileName: string;

  constructor(private httpClient: HttpClient,
              private errorService: ErrorService) {
  }

  @HostListener('click') onClick() {
    this.httpClient.get(this.url, {responseType: 'blob', observe: 'response'}).subscribe(data => {
        const link = document.createElement('a');
        const blob = new Blob([data.body], {type: 'application/stream'});
        link.setAttribute('href', window.URL.createObjectURL(blob));
        const contentDisposition = data.headers.get('Content-disposition');
        if (contentDisposition) {
          link.setAttribute('download', contentDisposition.split('filename=')[1]);
        } else {
          link.setAttribute('download', this.fileName);
        }
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      },
      (error) => {
        this.errorService.occur({message: '导出文件错误', error: error});
      });
  }
}
